package algorithm;

public class PartitionAndQuickSort {


    public static void swap(int[] arr,int i,int j){
        int a=arr[i];
        arr[i]=arr[j];
        arr[j]=a;
    }
    public static int partition (int[] arr, int L,int R){
        if(L>R)
            return -1;
        if(L==R)
            return L;
        int index=L;
        int lessEqual=L-1;
        while(index<R){
            if(arr[index]<=arr[R]){
                swap(arr,++lessEqual,index++);
            }else {
                index++;
            }
        }
        swap(arr,++lessEqual,R);
        return lessEqual;

    }

    public static int[] partition2(int[] arr,int L, int R){
        if(L>R){
            return new int[]{-1,-1};
        }
        if(L==R){
            return new int[]{L,R};
        }

        int index=L;
        int less=L-1;
        int more=R;
        while(index<more){
            if(arr[index]<arr[R]){
                swap(arr,++less,index++);
            }else
            if(arr[index]==arr[R]){
                index++;
            }else
            if(arr[index]>arr[R]){
                swap(arr,index,--more);
            }
        }
        swap(arr,index,R);
        return new int[]{less++,more};
    }

    public static void process(int[] arr, int L, int R){

        if(L>=R){
            return;
        }

        swap(arr,L+(int)(Math.random()*(R-L+1)),R);//以随机数作为基数
        int[] partition = partition2(arr, L, R);
        process(arr,L,partition[0]-1);
        process(arr,partition[1]+1,R);
    }

    public static void quickSort(int[] arr){
        process(arr,0,arr.length-1);
    }


    public static void main(String[] args) {
        int[] arr={2,12,5,4,8,7,9,8,10};
        quickSort(arr);
        for (int i = 0; i < arr.length; i++) {
            System.out.println(arr[i]);
        }
    }
}
